package pt.record.model;

import design.patterns.observer.Subject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.prefs.Preferences;

import static pt.record.model.Record.MATCHES;

/**
 * Created by nuno-rafael-figueiredo on 15-03-2014.
 */
public class DirectMatches extends Subject {

    private static final Preferences PREFERENCES = Preferences.systemNodeForPackage(DirectMatches.class);
    private static final int DELAY = PREFERENCES.getInt("delay", 30 * 1000);

    private Map<String, Matches> map;

    DirectMatches() {
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                Document document;
                try {
                    document = Jsoup.connect(Record.URL).get();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                Map<String, Matches> map = new LinkedHashMap<>();
                Elements boxes = document.select("#JEDOpened .liveScoreBox1");
                for (Element box : boxes)
                    handleBox(map, box);

                DirectMatches.this.map = map;
                setChanged();
                notifyObservers(map);
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, DELAY);
    }

    private void handleBox(Map<String, Matches> map, Element box) {
        String header = box.select(".liveScoreBox1Header").get(0).text();
        Matches matches = new Matches();
        Elements content = box.select(".liveScoreBox1Content");
        for (Element contentItem : content)
            matches.add(MATCHES.create(contentItem));

        map.put(header, matches);
    }

    public Map<String, Matches> getMap() {
        return map;
    }
}
